<template>
    <Dialog :title="comInfo.name" :show="true" @close="cancel" :width="480" :height="350" :left="uiLeft" :top="uiTop">
        <!-- 功能按钮 -->
        <div class="cimrts-menu">
            <div class="menu-left">
                <FucMenuList :menuList="heightMenuList" @clickComponent="clickComponent" :isDisabled="false"
                    :isChecked="true" />
            </div>

            <div class="menu-right">
                <el-button @click.stop="BatchDelete" class="alert-btn"> 批量删除</el-button>
                <el-button @click=" currentDialog = 'submit'"> 提交</el-button>
            </div>
        </div>
        <div class="center-table">
            <el-table :data="maskListsRef" border :cell-style="cellStyle2" :header-cell-style="cellStyleSmall"
                :highlight-current-row="false" @selection-change="handleSelectionChange">
                <!-- <el-table-column type="index" label="序号" width="60" align="center" :show-overflow-tooltip="true" /> -->
                <el-table-column type="selection" width="35" align="center" />
                <el-table-column prop="name" align="center" label="名称" width="120" :show-overflow-tooltip="true" />
                <el-table-column align="center" label="操作" width="auto">
                    <template #default="scope">
                        <div id="table-operation">
                            <el-button size="small" text @click="locationClipPolygon(scope.row)">
                                <img src="@/assets/common/dingwei.png" /> 定位
                            </el-button>
                            <el-button size="small" text @click="edit(scope.row)">
                                <img src="@/assets/common/editing.png" /> 编辑
                            </el-button>
                            <el-button size="small" text @click="modifyClipPolygonName(scope.row)">
                                <img src="@/assets/common/name.png" /> 修改名称
                            </el-button>
                            <el-button size="small" text @click="deleteClip(scope.row)">
                                <img src="@/assets/common/shanchu.png" /> 删除
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </Dialog>
    <TooltipCom v-if="currentDialog == 'submit'" :content="'确认提交吗？'" :title="'提交'" :isVisible="true"
        @close="currentDialog = undefined" @confirm="submitConfirm" />

    <TooltipCom v-if="currentDialog == 'delete'" :content="'确认删除吗？'" :title="'删除'" :isVisible="true"
        @close="currentDialog = undefined" @confirm="deleteConfirm" />

    <TooltipCom v-if="currentDialog == 'batchDel'" :content="'确认删除吗？'" :title="'删除'" :isVisible="true"
        @close="currentDialog = undefined" @confirm="batchDelConfirm" />

    <DialogCom v-if="currentDialog == 'modifyClipPolygonName'" :draggable="true" :title="'修改裁剪多边形'" :visible="true"
        :content="'确认提交吗？'" @close="currentDialog = undefined" @confirm="confirmModifyClipPolygonName">
        <template v-slot:content>
            <div class="clip_box">
                <div class="clip_title">名称:</div>
                <el-input v-model="info.name" class="ipt" />
            </div>
        </template>
    </DialogCom>

    <UploadShp v-if="currentDialog == 'uploadShp'" :title="'上传SHP'" :isVisible="true" @close="currentDialog = undefined"
        @confirm="confirmUploadShp" type="ClipPolygon"></UploadShp>

    <UploadGeoJson v-if="currentDialog == 'geojson'" :title="'上传GeoJSON'" :isVisible="true"
        @close="currentDialog = undefined" @confirm="confirmUploadGeoJSON" type="ClipPolygon"></UploadGeoJson>

    <TooltipCom v-if="currentDialog == 'shpLength'" :content="`创建的裁剪多边形数量为 ${shpInfo.features.length} 个，超过了最大创建数100个。点击确定后请稍等，系统将只创建前100个要素。您是否要继续？
`" :title="'提示'" :isVisible="true" @close="currentDialog = undefined" @confirm="confirmShpLength" />

    <TooltipCom v-if="currentDialog == 'geojsonLength'" :content="`创建的裁剪多边形数量为 ${geojsonInfo.features.length} 个，超过了最大创建数100个。点击确定后请稍等，系统将只创建前100个要素。您是否要继续？
`" :title="'提示'" :isVisible="true" @close="currentDialog = undefined" @confirm="confirmGeoJsonLength" />

</template>
<script setup lang="ts">

import { heightMenuList } from "@/scripts/menu/terrainrts/heightMenuList";
import Dialog from "@/components/Dialog.vue";
import DialogCom from "@/components/common/DialogCom.vue";
import { onBeforeUnmount, onMounted, ref, watch, nextTick } from "vue";
import { cellStyle2, cellStyleSmall } from "../../scripts/tableStyle";
import { getProjectManager } from "../../scripts/getProjectManager";
import { createVueDisposer, toVR, } from "earthsdk-ui";
import TooltipCom from "../../components/common/TooltipCom.vue";
import { ElMessage } from "element-plus";
import FucMenuList from "@/components/common/FucMenuList.vue";
import UploadShp from "./UploadShp.vue";
import UploadGeoJson from "./UploadGeoJson.vue";

const props = withDefaults(defineProps<{ comInfo: any }>(), {});
const emits = defineEmits(["cancel"]);
const cancel = () => {
    emits("cancel", props.comInfo.id);
};
const uiLeft = document.body.clientWidth - 10 - 480;

const uiTop = 60;

const d = createVueDisposer(onBeforeUnmount);

const objm = getProjectManager();
const terrainrtsManager = objm.terrainrtsManager;
const clipPolygon = terrainrtsManager.clipPolygon
// 裁剪区域列表
const maskListsRef = toVR<any>(d, [clipPolygon, "maskLists"]);



const currentDialog = ref<any>(undefined)
const items = ref([])

// 鼠标点击组件
const clickComponent = (item: any) => {
    if (item.id === 'submit') {
        currentDialog.value = 'submit'
        return;
    }
    if (item.id === 'shp') {
        currentDialog.value = 'uploadShp'
        return;
    }
    if (item.id === 'geojson') {
        currentDialog.value = 'geojson'
        return;
    }
    if (item.id === 'download') {
        if (!items.value.length) {
            ElMessage({
                message: '请先勾选裁剪多边形',
                type: 'warning',
            })
        } else {
            terrainrtsManager.downloadGeoJSON(items.value, "裁剪多边形")
        }
        return;
    }
    clipPolygon.createEvent.emit(item.id)
    item.status != "active" ? item.status = "active" : item.status = "none";
    if (item.status == "none") {
        clipPolygon.createEvent.emit("")
    }
}

// 提交 确定
const submitConfirm = async () => {
    await clipPolygon.createMaskPolygon()
    currentDialog.value = undefined

}


// 定位
const locationClipPolygon = (row: any) => {
    clipPolygon.flyToMask(row)
}
// 编辑
const edit = (row: any) => {
  const sceneObject = clipPolygon.maskMap.get(row.id)
  sceneObject.editing = true
}
const info = ref<any>({})
let selectedClipId = ref("")

// 修改
const modifyClipPolygonName = (row: any) => {
    info.value.name = row.name

    selectedClipId.value = row.id
    currentDialog.value = 'modifyClipPolygonName'
}

// 修改名称 确定
const confirmModifyClipPolygonName = () => {
    const index = maskListsRef.value.findIndex((item: any) => item.id === selectedClipId.value)
    const item = maskListsRef.value[index]
    item.name = info.value.name

    maskListsRef.value.splice(index, 1, item)
    ElMessage.success("修改成功")
    currentDialog.value = undefined
}

// 删除
const deleteClip = (row: any) => {
    selectedClipId.value = row.id
    currentDialog.value = 'delete'
}

// 删除 确定
const deleteConfirm = () => {
    const index = maskListsRef.value.findIndex((item: any) => item.id === selectedClipId.value)
    maskListsRef.value.splice(index, 1)
    if (clipPolygon.maskMap.has(selectedClipId.value)) {
        objm.destroySceneObject(clipPolygon.maskMap.get(selectedClipId.value))
        clipPolygon.maskMap.delete(selectedClipId.value)
    }
    ElMessage.success("删除成功")
    currentDialog.value = undefined
}

const ids = ref([])

/** 多选 拿到id数组*/
const handleSelectionChange = (val: any) => {
    items.value = val
    ids.value = val.map((item: any) => item.id)
}


// 批量删除
const BatchDelete = () => {
    if (ids.value.length == 0) return ElMessage.error('请先勾选裁剪多边形')
    currentDialog.value = 'batchDel'
}

const batchDelConfirm = () => {
    ids.value.forEach((id) => {
        const index = maskListsRef.value.findIndex((item: any) => item.id == id)
        maskListsRef.value.splice(index, 1)
        if (clipPolygon.maskMap.has(id)) {
            objm.destroySceneObject(clipPolygon.maskMap.get(id))
            clipPolygon.maskMap.delete(id)
        }
    })
    currentDialog.value = undefined
    ElMessage.success('删除成功')
}

const shpInfo = ref<any>([])

// 上传SHP确定
const confirmUploadShp = (data: any) => {
    shpInfo.value = []
    if (data.features.length > 100) {
        currentDialog.value = "shpLength"
        shpInfo.value = data
    } else {
        clipPolygon.createPolygonsByShp(data)
        currentDialog.value = undefined
    }
}
const confirmShpLength = () => {
    const { features, ...e } = shpInfo.value
    const data = {
        features: features.slice(0, 100),
        ...e
    }
    clipPolygon.createPolygonsByShp(data)
    currentDialog.value = undefined
}

const geojsonInfo = ref<any>([])


// 上传geojson确定
const confirmUploadGeoJSON = (data: any) => {
    geojsonInfo.value = []
    if (data.features.length > 100) {
        currentDialog.value = "geojsonLength"
        geojsonInfo.value = data
    } else {
        clipPolygon.createPolygonsByGeonJson(data)
        currentDialog.value = undefined
    }
}

const confirmGeoJsonLength = () => {
    const { features, ...e } = geojsonInfo.value
    const data = {
        features: features.slice(0, 100),
        ...e
    }
    clipPolygon.createPolygonsByShp(data)
    currentDialog.value = undefined
}

onMounted(async () => {
    await clipPolygon.getClipPolygon()
})

onBeforeUnmount(() => {
    clipPolygon.clear()
})

</script>
<style scoped>
.center-table {
    height: calc(100% - 60px);
    padding: 10px;
}

.cimrts-menu {
    background-color: #f0f0f0;
    width: calc(100%);
    height: 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px 0 0;
    box-sizing: border-box;
}

#table-operation img {
    width: 17px !important;
    height: 18px !important;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover>td) {
    background-color: transparent !important;
    color: #333 !important;

}

:deep(.el-table) {
    height: 100%;
    overflow-y: auto;
}

.switch {
    display: flex;
    justify-content: space-around;
}

.clip_title {
    width: 70px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
}

.clip_box {
    display: flex;
    margin-bottom: 15px;
}

.menu-left {
    width: 60%;
}

/* 批量删除按钮 */
.alert-btn {
    color: #F96F70;
    border: 1px solid #F96F70;
    background-color: rgba(249, 111, 112, 0);
}

.alert-btn:hover {
    color: #F96F70;
    border: 1px solid #F96F70;
    background-color: rgba(249, 111, 112, 0);
}

#table-operation .el-button+.el-button {
    margin-left: 0px;
}
</style>
